const { db, query } = require("../../db/db");
const util = require("util");
const redisClient = require("../../redis/redisClient.js");

async function GteArticleList(req, res) {
  const Filter = req.body.Filter;
  const ArticleType = req.body.ArticleType;
  let PageSize = req.body.PageSize;
  let PageNum = req.body.PageNum;
  let Heat = req.body.Heat || 0;
  const PublisherId = req.body.PublisherId || "";
  let UserId = req.params.username;

  let sql_condition = "";
  let HeatStatus = "PublishTime";

  if (Heat) {
    HeatStatus = "PageView";
  }

  if (!PageSize) {
    PageSize = 10;
  }
  if (!PageNum) {
    PageNum = 1;
  }

  if (!PublisherId && PublisherId !== 0) {
    if (!(Filter == undefined || Filter == "")) {
      if (
        !(
          ArticleType == undefined ||
          ArticleType == "" ||
          ArticleType == "综合"
        )
      ) {
        sql_condition += util.format(
          'Where ArticleType="%s" \
          AND (ArticleTitle like "%%%s%" OR ArticleContent like "%%%s%")',
          ArticleType,
          Filter,
          Filter
        );
      } else {
        sql_condition += util.format(
          'Where ArticleTitle like "%%%s%" OR ArticleContent like "%%%s%"',
          Filter,
          Filter
        );
      }
    } else {
      if (
        !(
          ArticleType == undefined ||
          ArticleType == "" ||
          ArticleType == "综合"
        )
      ) {
        sql_condition += util.format('Where ArticleType="%s"', ArticleType);
      }
    }
  } else {
    if (!(Filter == undefined || Filter == "")) {
      if (
        !(
          ArticleType == undefined ||
          ArticleType == "" ||
          ArticleType == "综合"
        )
      ) {
        sql_condition += util.format(
          'Where ArticleType="%s" \
          AND (ArticleTitle like "%%%s%" OR ArticleContent like "%%%s%") AND PublisherId=%s',
          ArticleType,
          Filter,
          Filter,
          PublisherId
        );
      } else {
        sql_condition += util.format(
          'Where PublisherId=%s AND (ArticleTitle like "%%%s%" OR ArticleContent like "%%%s%")',
          PublisherId,
          Filter,
          Filter
        );
      }
    } else {
      console.log("55555", PublisherId);
      if (
        !(
          ArticleType == undefined ||
          ArticleType == "" ||
          ArticleType == "综合"
        )
      ) {
        sql_condition += util.format(
          'Where ArticleType="%s" AND PublisherId=%s',
          ArticleType,
          PublisherId
        );
      } else {
        sql_condition += util.format("Where PublisherId=%s", PublisherId);
      }
    }
  }

  const select_article_list_sql = util.format(
    "Select \
    ArticleId, \
    IFNULL(ArticleTitle,'') as ArticleTitle, \
    IFNULL(Abstract,'') as Abstract, \
    IFNULL(ArticleContent,'') as ArticleContent, \
    IFNULL(User.UserName,'') as PublisherName, \
    IFNULL(PublishTime,'') as PublishTime, \
    LikeNum, \
    Collect, \
    PageView, \
    CommentNum,\
    IFNULL(ArticleTabs,'') as ArticleTabs, \
    IFNULL(ArticleImgUrl,'') as ArticleImgUrl \
    From Article LEFT JOIN User\
    ON Article.PublisherId=User.UserId\
    %s ORDER BY %s Desc Limit %s,%s",
    sql_condition,
    HeatStatus,
    (PageNum - 1) * PageSize,
    PageSize
  );

  const select_article_list_res = await query(select_article_list_sql);

  const resultWithLikes = await Promise.all(
    select_article_list_res.map(async (item) => {
      const articleId = item.ArticleId;
      const userKey = `article:like:users:${articleId}`;
      const countKey = `article:like:count:${articleId}`;
      const isLiked = await redisClient.sismember(userKey, UserId);
      let likeCount = await redisClient.get(countKey);
      if (likeCount === null) {
        const likeCountSql = util.format(
          "select count(*) as count from Article_Like_Info where ArticleId=%s",
          articleId
        );
        const likeCountRes = await query(likeCountSql);
        likeCount = likeCountRes[0]?.count || 0;
        await redisClient.set(countKey, likeCount);
      }
      return {
        ...item,
        isLike: isLiked ? 1 : 0,
        likeCount: Number(likeCount),
      };
    })
  );

  res.send({
    status: 0,
    ArticleList: resultWithLikes,
  });
}

module.exports = { GteArticleList };
